<!--
 * @Description: 
 * @Author: @yangwenshan
 * @since: 2021-05-13 15:36:56
 * @LastAuthor: @yangwenshan
 * @lastTime: 2021-05-19 16:57:48
-->
<template>
  <a-drawer title="Banner详情" width="40%" placement="right" :visible="visible" @close="onClose">
    <a-spin tip="数据加载中" :spinning="loading">
      <a-form
        :form="form"
        @submit="handleSubmit"
        layout="horizontal"
        :labelCol="{ span: 3 }"
        :wrapperCol="{ span: 21 }"
      >
        <a-form-item label="名称">
          <a-input
            :disabled="mode === 'check'"
            placeholder="请输入名称"
            v-decorator="['name', { initialValue: data.name, rules: [{ required: true, message: '请输入名称' }] }]"
          />
        </a-form-item>
        <a-form-item label="主图">
          <div class="clearfix">
            <a-upload
              :disabled="mode === 'check'"
              list-type="picture-card"
              :file-list="mainImgList"
              @preview="handlePreview"
              accept=".jpg,.png,.jpeg,.PNG,.JPG,.JPEG"
              :remove="handleRemove1"
              :before-upload="beforeUpload"
              @change="uploadChange(1)"
              v-decorator="[
                'mainImgList',
                {
                  initialValue: mainImgList,
                  rules: [
                    {
                      required: true,
                      message: '请上传主图',
                    },
                  ],
                },
              ]"
            >
              <div v-if="mainImgList.length < 1">
                <a-icon type="plus" />
                <div class="ant-upload-text">上传</div>
              </div>
            </a-upload>
            <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
              <img alt="example" style="width: 100%" :src="previewImage" />
            </a-modal>
          </div>
        </a-form-item>
        <a-form-item label="详情图">
          <div class="clearfix">
            <a-upload
              list-type="picture-card"
              :disabled="mode === 'check'"
              :file-list="detailsImgList"
              @preview="handlePreview"
              accept=".jpg,.png,.jpeg,.PNG,.JPG,.JPEG"
              :remove="handleRemove2"
              :before-upload="beforeUpload"
              @change="uploadChange(2)"
              v-decorator="[
                'detailsImgList',
                {
                  initialValue: detailsImgList,
                  rules: [
                    {
                      required: true,
                      message: '请上传详情图',
                    },
                  ],
                },
              ]"
            >
              <div v-if="detailsImgList.length < 4">
                <a-icon type="plus" />
                <div class="ant-upload-text">上传</div>
              </div>
            </a-upload>
            <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
              <img alt="example" style="width: 100%" :src="previewImage" />
            </a-modal>
          </div>
        </a-form-item>
        <a-form-item label="备注">
          <a-textarea
            :disabled="mode === 'check'"
            placeholder="请输入备注"
            :auto-size="{ minRows: 6, maxRows: 10 }"
            v-decorator="['remark', { initialValue: data.remark, rules: [{ required: false, message: '请输入备注' }] }]"
          />
        </a-form-item>
        <a-form-item v-show="['add', 'edit'].includes(mode)" :wrapper-col="{ span: 12, offset: 3 }">
          <a-button :loading="btnLoading" type="primary" html-type="submit">
            {{ mode === 'edit' ? '保存' : '新增' }}
          </a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-drawer>
</template>

<script>
import { getBannerDetail, addBannerList, updateBanner } from '@/api/banner'
import request from '@/utils/request'
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}
export default {
  data() {
    return {
      data: {},
      visible: false,
      mode: 'check',
      mainImgList: [],
      detailsImgList: [],
      previewVisible: false,
      previewImage: '',
      form: this.$form.createForm(this),
      loading: false,
      btnLoading: false,
    }
  },
  methods: {
    showDrawer(id, mode = 'add') {
      this.visible = true
      this.mode = mode
      if (['check', 'edit'].includes(mode)) {
        this.getDetail(id)
      }
    },
    onClose() {
      this.visible = false
    },
    getDetail(id) {
      this.loading = true
      getBannerDetail(id)
        .then((res) => {
          this.data = res
          if (res.parent_url) {
            this.mainImgList = [
              {
                uid: 1,
                name: `image_1`,
                status: 'done',
                url: res.parent_url,
              },
            ]
          }
          if (res.child_urls) {
            this.detailsImgList = res.child_urls.map((item, index) => {
              return {
                uid: index,
                name: `image_${index}`,
                status: 'done',
                url: item,
              }
            })
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    init() {
      this.form.resetFields()
      this.data = {}
      this.mainImgList = []
      this.detailsImgList = []
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          const data = {
            ...values,
          }
          data.parent_url = this.mainImgList[0].url
          data.child_urls = JSON.stringify(
            this.detailsImgList.map((item) => {
              return item.url
            })
          )
          if (this.mode === 'add') {
            this.add(data)
          } else if (this.mode === 'edit') {
            this.edit(this.data.id, data)
          }
        }
      })
    },
    add(data) {
      this.btnLoading = true
      addBannerList(data)
        .then((res) => {
          this.$message.success('新增成功')
          this.$emit('refresh')
          this.init()
          this.onClose()
        })
        .finally(() => {
          this.btnLoading = false
        })
    },
    edit(id, data) {
      this.btnLoading = true
      updateBanner(id, data)
        .then((res) => {
          this.$message.success('修改成功')
          this.$emit('refresh')
          this.init()
          this.onClose()
        })
        .finally(() => {
          this.btnLoading = false
        })
    },
    handleCancel() {
      this.previewVisible = false
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleRemove1(file) {
      const index = this.mainImgList.indexOf(file)
      const newFileList = this.mainImgList.slice()
      newFileList.splice(index, 1)
      this.mainImgList = newFileList
    },
    handleRemove2(file) {
      const index = this.detailsImgList.indexOf(file)
      const newFileList = this.detailsImgList.slice()
      newFileList.splice(index, 1)
      this.detailsImgList = newFileList
    },
    beforeUpload(file) {
      const isJpgOrPng = ['image/jpeg', 'image/png'].includes(file.type)
      if (!isJpgOrPng) {
        this.$notification['error']({
          message: '上传错误',
          description: '文件格式格式仅限于PNG,JPG',
        })
      }
      const isLt3M = file.size / 1024 / 1024 < 3
      if (!isLt3M) {
        this.$notification['error']({
          message: '上传错误',
          description: '文件大小不能超过3M',
        })
      }
      if (isJpgOrPng && isLt3M) {
        this.handleUpload(file)
      }
      return false
    },
    uploadChange(flag) {
      /**
       * @params flag
       * flag = 1,主图
       * flag = 2,详情图
       */
      this.flag = flag
    },
    handleUpload(file) {
      const formData = new FormData()
      formData.append('picture_byte', file)
      request.post('/picture/upload/', formData).then((res) => {
        if (this.flag === 1) {
          this.mainImgList.push({
            uid: new Date().getTime(),
            name: 'image',
            status: 'done',
            url: res.img_url,
          })
        } else if (this.flag === 2) {
          this.detailsImgList.push({
            uid: new Date().getTime(),
            name: 'image',
            status: 'done',
            url: res.img_url,
          })
        }
      })
    },
  },
}
</script>
